//
//  FMRemotePlayerFile.m
//  FMRemotePlayer
//
//  Created by apple on 17/3/14.
//  Copyright © 2017年 appbanana. All rights reserved.
//

#import "FMRemotePlayerFile.h"
#import <MobileCoreServices/MobileCoreServices.h>

#define kCache NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject
#define kTemp NSTemporaryDirectory()

@implementation FMRemotePlayerFile

+ (NSString *)cacheAudioFilePath:(NSURL *)url{
    
    return [kCache stringByAppendingPathComponent:url.lastPathComponent];
}

+ (NSString *)tempAudioFilePath:(NSURL *)url{
    return [kTemp stringByAppendingPathComponent:url.lastPathComponent];
}

+ (BOOL)fileExistsAtPath:(NSString *)path;
{
    return [[NSFileManager defaultManager] fileExistsAtPath:path];
}

+ (BOOL)fileExistsWithAudioURL:(NSURL *)url{
    NSString *filePath = [self cacheAudioFilePath:url];
    return [self fileExistsAtPath:filePath];
}

+ (long long)fileSizeWithAudioURL:(NSURL *)url{
    NSString *filePath = [self cacheAudioFilePath:url];
    if (![self fileExistsAtPath:filePath]) {
        return 0;
    }
    NSDictionary *infoDic = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    return [infoDic[NSFileSize] longLongValue];
}

+ (NSString *)contentTypeWithURL:(NSURL *)url{
    NSString *fileExtension = [self cacheAudioFilePath:url].pathExtension;
    CFStringRef contentTypeCF = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef _Nonnull)(fileExtension), NULL);
    NSString *contenType = CFBridgingRelease(contentTypeCF);
    return contenType;
}

+ (void)moveTmpFileToCacheFileWithURL:(NSURL *)url{
    NSString *cachePath = [self cacheAudioFilePath:url];
    NSString *tempPath = [self tempAudioFilePath:url];
    [[NSFileManager defaultManager] moveItemAtPath:tempPath toPath:cachePath error:nil];
}

+ (void)removeTempFileWithURL:(NSURL *)url{
    NSString *filePath = [self tempAudioFilePath:url];
    BOOL isDirectory;
    [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
    if (!isDirectory) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    }
}


@end
